package org.bookshare.document.beans;

import java.io.File;
import java.io.IOException;

import org.bookshare.document.daisy.OPFPackageFile;
import org.jdom.Document;
import org.jdom.JDOMException;

/**
 * Useful methods for various DocumentSets.
 * @author Reuben Firmin
 */
public final class DocumentWrapperFactory implements HasOPF, HasXML {

	private OPFPackageFile packageFile;
	private DocumentSet docSet;

	/**
	 * Construct with the document set that is going to be served by this factory.
	 * @param docSet Not null
	 */
	public DocumentWrapperFactory(final DocumentSet docSet) {
		this.docSet = docSet;
	}

	/**
	 * {@inheritDoc}
	 */
	public OPFPackageFile getOPFPackageFile()
	throws JDOMException, IOException
	{
		if (!docSet.getType().containsComponent(DocumentComponent.OPF)) {
			return null;
		}

		if (packageFile != null) {
			return packageFile;
		}

		if (!docSet.hasBeenParsed(DocumentComponent.OPF)) {
    		docSet.createDocuments(DocumentComponent.OPF, false);
    	}
		if (docSet.getDocument(DocumentComponent.OPF) == null) {
			return null;
		}
    	packageFile = new OPFPackageFile(docSet.getFile(DocumentComponent.OPF),
    			docSet.getDocument(DocumentComponent.OPF));
    	return packageFile;
	}

	/**
	 * {@inheritDoc}
	 */
	public Document getOPFDocument() {
		return docSet.getDocument(DocumentComponent.OPF);
	}

	/**
	 * {@inheritDoc}
	 */
	public File getOPFFile() {
		return docSet.getFile(DocumentComponent.OPF);
	}

	/**
	 * {@inheritDoc}
	 */
	public Document getXMLDocument() {
		return docSet.getDocument(DocumentComponent.XML);
	}

	/**
	 * {@inheritDoc}
	 */
	public File getXMLFile() {
		return docSet.getFile(DocumentComponent.XML);
	}
}
